package org.batatasframework.support.searchable.writer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.batatasframework.support.searchable.ResultHeadInfo;
import org.batatasframework.support.searchable.SearchableInputStream;
import org.batatasframework.support.searchable.result.ResultRow;


public class ObjectResultWriter extends AbstractResultWriter{
	private ResultHeadInfo[][] heads;
	
	private final List<Object> rows = new ArrayList<>();
	private transient List<Object> line;
	
	public ObjectResultWriter(SearchableInputStream inputStream) throws Exception {
		super(inputStream);
	}
	
	@Override
	protected void renderHead(ResultHeadInfo[][] heads) {
		this.heads = heads;
	}

	private void appendToList(){
		if(null != line){
			replaceIlegalChars(line);
			rows.add(line);
			line = null;
		}
	}
	/*
	 * 定义将json中无法识别的字符转换为合法的字符
	 */
	final static Map<String,String> replaceMap = new HashMap<String,String>();
	static{
		replaceMap.put(">", "&gt;");
		replaceMap.put("<", "&lt;");
		// ...
	}

	private void replaceIlegalChars(List<Object> arr) {
		int k = 0;
		for(Object o : arr){
			if(o instanceof String){
				String s = (String) o;
				for(String  key : replaceMap.keySet()){
					if(s.contains(key)){
						s = s.replaceAll(key, replaceMap.get(key));
						arr.set(k, s);
					}
				}
			}
			
			k++;
		}
	}
	
	@Override
	public void group(Object value, int size) {
		appendToList();
		rows.add(value);
	}
	
	@Override
	public void newLine() {
		appendToList();
		line = new ArrayList<>();
	}
	
	@Override
	public void append(Object value) {
		line.add(value);
	}
	
	@Override
	public void renderBody(List<? extends ResultRow> rows) throws Exception {
		super.renderBody(rows);
		appendToList();
	}
	
	public ResultHeadInfo[][] getHeads() {
		return heads;
	}
	
	public List<Object> getRows() {
		return rows;
	}
}
